/* eslint-disable no-param-reassign */
import React, { useEffect, useMemo, useRef, useState } from 'react';
import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { Button, Dialog, Form, Input, Message, Table, Upload } from '@alifd/next';
import { t } from '@lingui/macro';
import { observable } from 'mobx';
import { observer } from 'mobx-react-lite';
import { FieldsGrid, TitleGrid } from '../stores/definitions';
import TauTable from '@/components/TauTable';
import { uniqueId } from 'lodash';
import AttachmentPanel from './AttachmentPanel';

const FromItem = Form.Item;

const tableId = uniqueId('tauTable-');

function ActivityForm({ id, modal, tabIdx, onSubmit, onCancel }) {
  const { activityStore: store } = useStore();
  const [activity] = useState(() => observable({}));
  const [isViewMode] = useState(modal[0] === 'view');
  const formProps = isViewMode ? { field: false } : {};
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [state, setState] = useState([]);
  const [extras, setExtras] = useState([]);
  const [tabActive, setTabActive] = useState('');
  const [currentPage, setCurrentPage] = useState(0); // 默认页数
  const [pageSize, setPageSize] = useState(10); // 每页显示的数据数量
  const [idx, setIdx] = useState();
  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    if (id) {
      (async () => {
        const data = await store.get(id);
        editCtx.origin = _.cloneDeep(data);
        _.assign(activity, data);
        setState(data?.whiteList);
        if (data?.extra) {
          const toggleExtra = Object.entries(data?.extra).map(([itemId, content]) => ({ itemId, content }));
          setExtras(toggleExtra);
        }
      })();
    } else {
      _.set(activity, 'enabled', true);
      _.set(activity, 'whiteList', []);
      _.set(activity, 'noticeConfigure.monitorType', '0');
    }
    setTabActive(tabIdx);
  }, []);

  // 服务车票 买票时减去价格  三张票价格来自这张优惠券  花钱买的团购券  未核销就得全款退

  const memoNameValue = useMemo(() => {
    return extras;
  }, [extras, idx]);

  const overrideModel = {
    extra: {
      ui: {
        renderer: (__) => renderTable,
        span: 4,
      },
    },
    activePageSetting: {
      attachments: {
        ui: {
          renderer: (r) => <AttachmentPanel activity={activity} mode={modal[0]} />,
          span: 4,
        },
      },
    },
  };

  const handleAddState = () => {
    const data = {
      itemId: '',
      content: '',
    };
    setExtras((pre) => {
      const cloneData = [...pre];
      cloneData.push(data);
      return cloneData;
    });
  };

  const handelChangeName = (v) => {
    setExtras((pre) => {
      const toggle = [...pre];
      toggle[idx].itemId = v;
      return toggle;
    });
  };

  const handleChangeContent = (v) => {
    setExtras((pre) => {
      const toggle = [...pre];
      toggle[idx].content = v;
      return toggle;
    });
  };

  const handleRemoveExtra = (i) => {
    setExtras((pre) => {
      const arr = [...pre];
      arr.splice(i, 1);
      return arr;
    });
  };

  const renderTable = useMemo(() => (
    <>
      <Button type="primary" style={{ marginBottom: 10 }} onClick={handleAddState}>{t`添加属性`}</Button>
      <Table
        hasBorder={false}
        dataSource={memoNameValue}
        columns={[
          {
            title: t`序号`,
            dataIndex: 'id',
            align: 'center',
            cell: (v, i) => <span>{i + 1}</span>,
          },
          {
            title: t`标识`,
            dataIndex: 'itemId',
            width: 300,
            align: 'center',
            cell: (v, i) => <Input onChange={(e) => handelChangeName(e, i)} style={{ width: '100%' }} value={v} />,
          },
          {
            title: t`内容`,
            dataIndex: 'content',
            width: 400,
            align: 'center',
            cell: (v, i) => <Input onChange={(e) => handleChangeContent(e, i)} style={{ width: '100%' }} value={v} />,
          },
          {
            title: t`操作`,
            dataIndex: 'name',
            align: 'center',
            cell: (v, i) => (
              <>
                <Button type="primary" text style={{ color: 'red' }} onClick={() => handleRemoveExtra(i)}>{t`删除`}</Button>
              </>
            ),
          },
        ]}
        onRowClick={(_, index) => setIdx(index)}
      />
    </>
  ), [memoNameValue, handleAddState, handelChangeName, handleChangeContent, handleRemoveExtra]);

  if (!activity) return <></>;

  // 根据当前页码和每页数量获取当前页需要显示的数据
  const startIndex = currentPage * pageSize;
  const endIndex = startIndex + pageSize;
  const currentPageData = state?.slice(startIndex, endIndex);

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(activity, name, value);
    if (name === 'type') {
      setTabActive(value);
    }
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleAddUser = async () => {
    const { phone_user } = activity;
    if (!phone_user) {
      return Message.warning({ content: t`请输入手机号!` });
    }
    if (phone_user.length !== 11) {
      return Message.warning({ content: t`请输入正确手机号!` });
    }
    try {
      const findUser = state.find((p) => p === phone_user);
      if (findUser) {
        return Message.warning({ content: t`该手机号已存在!` });
      }
      const res = await store.getUserMobile(phone_user);
      if (res) {
        setState((pre) => {
          const arr = [...pre];
          arr.push(phone_user);
          return arr;
        });
      } else {
        Message.error({ content: t`该用户非平台用户!` });
      }
    } catch (error) {
      Message.error({ content: t`添加失败`, duration: 7000 });
      throw error;
    }
  };

  const handleDeleteState = (i) => {
    setState((pre) => {
      const arr = [...pre];
      arr.splice(i + (currentPage * pageSize), 1);
      return arr;
    });
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: ActivityForm.jsx:213 _ errors:', errors);
      return;
    }
    const toggleExtra = extras?.reduce((acc, item) => {
      const { itemId, content } = item;
      acc[itemId] = content;
      return acc;
    }, {});
    _.set(activity, 'extra', toggleExtra);
    _.set(activity, 'whiteList', state);
    const { noticeConfigure } = activity;
    if (noticeConfigure.monitorType === 0) {
      _.set(activity, 'noticeConfigure.value', noticeConfigure.value / 100);
    }
    onSubmit?.(activity);
  };

  return (
    <Form
      isPreview={isViewMode}
      {...formProps}
      value={activity}
      colon
      onChange={handleChange}
      useLabelForErrorMessage
      style={{ marginTop: 20 }}
    >
      <TitleGrid title={t`基本信息`} />
      <FieldsGrid
        formData={activity}
        mode={modal[0]}
        columns={4}
        fields={[
          'type', 'name', 'noticeConfigure.monitorType',
          'noticeConfigure.value', 'enabled', 'link',
        ]}
        overrideModel={overrideModel}
      />
      <TitleGrid title={t`活动界面设置`} />
      <FieldsGrid
        formData={activity}
        mode={modal[0]}
        columns={4}
        fields={[
          'buttonText', 'link', 'attachments',
        ].map((p) => `activePageSetting.${p}`)}
        overrideModel={overrideModel}
      />
      <TitleGrid title={t`说明及其他`} />
      <FieldsGrid
        formData={activity}
        mode={modal[0]}
        columns={4}
        fields={[
          'description',
          'extra',
        ]}
        overrideModel={overrideModel}
      />

      {tabActive === '1' &&
        <>
          <Form.Item
            label={t`白名单手机号`}
            labelAlign="left"
            name="phone_user"
          >
            <Input
              style={{ width: 300 }}
              placeholder="请输入手机号"
              addonAfter={<Button type="primary" onClick={handleAddUser}>添加</Button>}
            />
          </Form.Item>
          <Form.Item
            label={t`白名单列表`}
            labelAlign="top"
            name="list"
            labelCol={
              { span: 8 }
            }
            wrapperCol={{
              span: 19,
            }}
          >
            <TauTable
              instanceId={tableId}
              primaryKey="id"
              tableLayout="fixed"
              currentPage={currentPage}
              pageSize={pageSize}
              total={state.length}
              onFetch={({ page, size }) => {
                setCurrentPage(page);
                size && setPageSize(size);
              }}
              dataSource={currentPageData}
              columns={[
                { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.priceIdx(i, currentPage, pageSize) },
                {
                  title: t`手机号`,
                  dataIndex: '',
                  width: 400,
                  cell: (v, i, r) => r,
                },
                {
                  title: t`操作`,
                  dataIndex: '',
                  cell: (v, i) => <Button type="primary" text style={{ color: 'red' }} onClick={() => handleDeleteState(i)}>{t`删除`}</Button>,
                },
              ]}
            />
          </Form.Item>
        </>
      }

      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>

    </Form>
  );
}

export default observer(ActivityForm);

